#pragma once
#include <thread>
#include <mutex>
#include <condition_variable>
#include "EventLoop.hpp"
using namespace std;
// 定义子线程对应的结构体
class WorkerThread
{
public:
    WorkerThread(int index)
    {
        m_evLoop = nullptr; // 该反应堆模型中有一个任务队列
        m_thread = nullptr;
        m_threadID = thread::id();
       m_name = "SubThread-" + to_string(index);
    }
    ~WorkerThread()
    {
        assert(m_thread);
        delete m_thread;
    }
    
    // 启动xianc
    void run()
    {
        // 创建子线程
       m_thread=new thread(WorkerThread::running,this);
       unique_lock<mutex> locker(m_mutex);
       while (m_evLoop == nullptr)
       {
           // 等于NULL说明子线程还没有初始化完毕，阻塞主线程
           m_cond.wait(locker);
       }
   }
   
    inline class EventLoop* getEventLoop()
    {
        return m_evLoop;
    }
private:
    void running()
    {
    m_mutex.lock();
    m_evLoop = new class EventLoop(m_name);
    m_mutex.unlock();
    m_cond.notify_one();//唤醒一个线程
    m_evLoop->run();
}

private:
    thread::id m_threadID;
    string m_name;
    mutex m_mutex;
    thread *m_thread;          // 保存线程实例
    condition_variable m_cond; // 条件变量
    class EventLoop *m_evLoop;       // 反应堆  线程启动什么任务取决与evLoop中添加了什么任务
};
